/**
 * FB API Handler
 *
 * Performs calls to Facebook's API
 *
 * @package Torchd Framework
 * @subpackage Facebook
 * @author Jason Raede <jason@torchdm.com>
 */

torchd.FB.api = {
	/**
	 * Access token returned by the FB.login call.
	 *
	 * Used for all other calls for protected data
	 */
	accessToken: '',
	
	/**
	 * Handles initial user login
	 *
	 * @param string scope		The permissions you want to request. 
	 * 		See <http://developers.facebook.com/docs/reference/api/permissions/> 
	 *		for details
	 * @param function callback
	 */
	login: function(scope, callback) {
		if(!scope) scope = '';
		FB.login(function(response) {
	   		if (response.authResponse) {
	   			torchd.FB.api.accessToken = response.authResponse.accessToken;
	     		if(callback) callback(response);
	   		} else {
	     		console.log('User cancelled login or did not fully authorize.');
	   		}
	 	},
	 	{
	 		scope: scope
	 	});
	},
	
	/**
	 * Performs an API call
	 *
	 * @param string call			The graph ID or username of the content plus any
	 								additional parameters
	 * @param function callback		Callback function after receiving a response
	 */
	apiCall:function(call, callback) {
		var url = '/' + call;
		if(this.accessToken) {
			if(url.indexOf('?') > -1) url = url + 'accessToken=' + this.accessToken;
			else url = url + '?accessToken=' + this.accessToken;
		}
		FB.api(url, function(response) {
			if(callback) callback(response);
		});
	},
	
	init:function(appId, channelUrl, callback) {
		FB.init({
	      	appId      : appId, // App ID
	      	channelUrl : channelUrl, // Channel File
	      	status     : true, // check login status
	      	cookie     : true, // enable cookies to allow the server to access the session
	      	oauth      : true, // enable OAuth 2.0
	      	xfbml      : true,  // parse XFBML
	      	frictionlessRequests : true
	    });
	    FB.getLoginStatus(function(response) {
	    	if(callback) callback(response);
	    	
	    });
	}
};